package com.hss.thread.wait;

import java.util.Random;
import java.util.Vector;

import static java.lang.Thread.*;

/**  https://www.cnblogs.com/zl1991/p/6930160.html
 * . 使用join。这种方式其实并不是那么的优雅，将所有线程启动完之后还需要将所有线程都join，但是每次join都会阻塞，直到被join线程完成，
 * 很可能所有被阻塞线程已经完事了，主线程还在不断地join，貌似有点浪费，而且两个循环也不太好看。
 */
public class WaitThread_Join {
    public static final int TEST_THREAD_COUNT = 10;

    public static void printSortedResult(Vector<Integer> list) {
        for (Integer item : list) {
            System.out.println(item == null ? "null" : item);
        }
    }


    public static void test() {
        final Vector<Integer> list = new Vector<Integer>();
        Thread[] threads = new Thread[TEST_THREAD_COUNT];
        Random random = new Random();
        try {
            for (int i = 0; i < TEST_THREAD_COUNT; i++) {
                final int num = i;
                threads[i] = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            sleep(random.nextInt(100));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        list.add(num);
                        System.out.printf(num + " add.\t");
                    }
                });
                threads[i].start();
            }
            for (int i = 0; i < TEST_THREAD_COUNT; i++) {
//如果join()方法在一个线程实例上调用，当前运行着的线程将阻塞直到这个线程实例完成了执行。
                threads[i].join();

                System.out.print(i + " end.\t");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        printSortedResult(list);
    }

    public static void main(String[] args) {
        test();
    }
}
